define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'quotation/index' + location.search,
                    add_url: 'quotation/add',
                    edit_url: 'quotation/edit',
                    del_url: 'quotation/del',
                    multi_url: 'quotation/multi',
                    import_url: 'quotation/import',
                    table: 'quotation',
                }
            });

            var table = $("#table");

            // 自定义操作栏按钮事件
            var operateEvents = {
                'click .btn-export-template': function (e, value, row, index) {
                    var url = 'quotation/export_template';
                    if (url) {
                        // 创建XMLHttpRequest对象
                        var xhr = new XMLHttpRequest();
                        xhr.open('POST', url, true);

                        // 设置请求头
                        xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
                        xhr.setRequestHeader('Content-Type', 'application/json');

                        // 将当前行数据添加到请求头
                        xhr.setRequestHeader('X-Record-Data', JSON.stringify(row));

                        xhr.onload = function() {
                            if (xhr.status === 200) {
                                // 处理响应数据
                                var blob = new Blob([xhr.response], {type: 'application/vnd.ms-excel'});
                                var downloadUrl = URL.createObjectURL(blob);
                                var a = document.createElement('a');
                                a.href = downloadUrl;
                                a.download = '报价单模板_' + new Date().toISOString().slice(0,19).replace(/[-:T]/g, '') + '.xls';
                                document.body.appendChild(a);
                                a.click();
                                document.body.removeChild(a);
                                URL.revokeObjectURL(downloadUrl);
                            } else {
                                Toastr.error('下载失败：' + xhr.statusText);
                            }
                        };

                        xhr.onerror = function() {
                            Toastr.error('网络错误，请重试');
                        };

                        // 发送请求
                        xhr.responseType = 'blob';
                        xhr.send();
                    } else {
                        Toastr.error('导出链接未配置');
                    }
                }
            };

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'customer_id', title: __('Customer_id')},
                        {field: 'product_id', title: __('Product_id')},
                        {field: 'price', title: __('Price'), operate:'BETWEEN'},
                        {field: 'created_at', title: __('Created_at')},
                        {field: 'updated_at', title: __('Updated_at')},
                        {field: 'operate', title: __('Operate'), table: table, events: operateEvents, formatter: Controller.api.formatter.operate}
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            // 使用jQuery给c-demand_id绑定change事件
            $('#c-demand_id').on('change', function() {
                Controller.updateProductInfo();
            })
            Controller.api.bindevent();
        },
        edit: function () {
            // 使用jQuery给c-demand_id绑定change事件
            $('#c-demand_id').on('change', function() {
                Controller.updateProductInfo();
            })
            Controller.api.bindevent();
            Controller.updateProductInfo();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            },
            formatter: {
                operate: function (value, row, index) {
                    var table = $('#table');
                    var that = $.fn.bootstrapTable.defaults;
                    var extend = that.extend;
                    var options = table.bootstrapTable('getOptions');
                    var id = row[options.pk];
                    var urls = {
                        edit: extend.edit_url + '?ids=' + id,
                        del: extend.del_url + '?ids=' + id,
                    };

                    var buttons = [
                        // '<a href="' + urls.edit + '" class="btn btn-xs btn-primary btn-editone" title="编辑">',
                        // '<i class="fa fa fa-edit"></i>',
                        // '</a> ',
                        // '<a href="javascript:;" class="btn btn-xs btn-danger btn-delone" title="删除">',
                        // '<i class="fa fa fa-trash"></i>',
                        // '</a> ',
                        '<a href="javascript:;" class="btn btn-xs btn-success btn-export-template" title="下载模板">',
                        '<i class="fa fa fa-file-excel-o"></i>',
                        '</a>'
                    ].join('');

                    return buttons;
                }
            }
        },
        updateProductInfo: function() {
            var productInfoInput = document.getElementById('product-info');
            var productId = $('#c-demand_id').val();
            if (productId) {
                // 发送AJAX请求获取产品信息
                $.ajax({
                    url: 'customer_demand/getProductInfoById', // 需要在控制器中创建此方法
                    type: 'GET',
                    data: {id: productId},
                    success: function(response) {
                        if (response) {
                            productInfoInput.value = response.name+'  '+response.number+'  '+response.alias+'  '+response.specifications+'  '+response.unit_price+'元'; // 设置产品信息
                        } else {
                            productInfoInput.value = '未找到产品信息';
                        }
                    },
                    error: function() {
                        productInfoInput.value = '获取产品信息失败';
                    }
                });
            } else {
                productInfoInput.value = '';
            }
        }
    };
    return Controller;
});
